package com.xysd.express.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.xysd.express.R;
import com.xysd.express.activity.logistics.EditLogisticsInfoActivity;
import com.xysd.express.activity.logistics.FareActivity;
import com.xysd.express.activity.logistics.ReceivingActivity;
import com.xysd.express.activity.logistics.ShipmentsActivity;
import com.xysd.express.base.BaseFragment;
import com.xysd.express.bean.CarInfoObj;
import com.xysd.express.bean.User;
import com.xysd.express.eventbus.LocationEvent;
import com.xysd.express.eventbus.LogisticsReceiveInfoEvent;
import com.xysd.express.eventbus.LogisticsSendInfoEvent;
import com.xysd.express.rx.RxBus;
import com.xysd.express.util.GlideImageLoader;
import com.xysd.express.util.TextUtil;
import com.xysd.express.util.ToastUtil;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.List;

import rx.Subscription;
import rx.functions.Action1;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.fragment_logistics)
public class LogisticsFragment extends BaseFragment implements View.OnClickListener {
    private String type;

    @ViewInject(R.id.banner)
    private Banner banner;
    @ViewInject(R.id.carType_tv)
    private TextView carType_tv;//车型
    @ViewInject(R.id.price_tv)
    private TextView price_tv;//加个
    @ViewInject(R.id.load_tv)
    private TextView load_tv;//载重
    @ViewInject(R.id.shape_tv)
    private TextView shape_tv;//形状（长宽高）
    @ViewInject(R.id.bulk_tv)
    private TextView bulk_tv;//容积
    @ViewInject(R.id.send_layout)
    private LinearLayout send_layout;//发货layout
    @ViewInject(R.id.receive_layout)
    private LinearLayout receive_layout;//收货layout

    @ViewInject(R.id.adds_send)
    private TextView adds_send;//发货地址
    @ViewInject(R.id.name_tel_send_tv)
    private TextView name_tel_send_tv;//发货姓名和电话
    @ViewInject(R.id.adds_receive)
    private TextView adds_receive;//收货地址
    @ViewInject(R.id.name_tel_receive_tv)
    private TextView name_tel_receive_tv;//收货姓名和电话
    @ViewInject(R.id.totle_money_tv)
    private TextView totle_money_tv;//总价格
    @ViewInject(R.id.price_details_tv)
    private TextView price_details_tv;//价格详情
    @ViewInject(R.id.order_now_btn)
    private TextView order_now_btn;//现在用车
    @ViewInject(R.id.order_appointment_layout)
    private LinearLayout order_appointment_layout;//预约用车

    private CarInfoObj.CarInfo carInfo;
    LogisticsSendInfoEvent sendInfoEvent;//发件信息
    LogisticsReceiveInfoEvent receiveInfoEvent;//收件信息

    Subscription rxSbscription_send, rxSbscription_receive, rxSbscription_location;

    LocationEvent location_send,location_receive;

    public LogisticsFragment setType(String type, CarInfoObj.CarInfo carInfo) {
        this.type = type;
        this.carInfo = carInfo;
        return this;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
        initRxBus();
    }

    @Override
    public void onDestroy() {
        if (!rxSbscription_send.isUnsubscribed()) {
            rxSbscription_send.unsubscribe();
        }
        if (!rxSbscription_receive.isUnsubscribed()) {
            rxSbscription_receive.unsubscribe();
        }
        super.onDestroy();
    }

    private void initRxBus() {
        rxSbscription_send = RxBus.getInstance().toObserverable(LogisticsSendInfoEvent.class)
                .subscribe(new Action1<LogisticsSendInfoEvent>() {
                    @Override
                    public void call(LogisticsSendInfoEvent event) {
                        Log.i("RxBus_send", event.toString());
                        sendInfoEvent = event;
                        adds_send.setText(event.adds);
                        name_tel_send_tv.setText(event.name + "  " + event.tel);
                    }
                });

        rxSbscription_receive = RxBus.getInstance().toObserverable(LogisticsReceiveInfoEvent.class)
                .subscribe(new Action1<LogisticsReceiveInfoEvent>() {
                    @Override
                    public void call(LogisticsReceiveInfoEvent event) {
                        Log.i("RxBus_Receive", event.toString());
                        receiveInfoEvent = event;
                        adds_receive.setText(event.adds);
                        name_tel_receive_tv.setText(event.name + "  " + event.tel);
                    }
                });

        rxSbscription_location =RxBus.getInstance().toObserverable(LocationEvent.class).subscribe(new Action1<LocationEvent>() {
            @Override
            public void call(LocationEvent locationEvent) {
                if (locationEvent.type.equals("send"))
                    location_send=locationEvent;
                else if (locationEvent.type.equals("receive"))
                    location_receive=locationEvent;
            }
        });

    }

    private void init() {
        send_layout.setOnClickListener(this);
        receive_layout.setOnClickListener(this);
        order_now_btn.setOnClickListener(this);
        order_appointment_layout.setOnClickListener(this);
        price_details_tv.setOnClickListener(this);
        setView();
    }


    //重写fragment是否对用户可视，当可视时加载数据（解决viewpager的预加载问题）
    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isCanLoadData();
    }

    private void isCanLoadData() {
        if (getUserVisibleHint()) {
            if (User.getInstance().isLogin) {
                //TODO

            }
        }
    }

    private void setView() {
        carType_tv.setText(carInfo.ShortDescription);
        new TextUtil().setTextColor(price_tv, carInfo.Price + "元/公里", 0, (carInfo.Price + "").length(), "#fa0d09");
        load_tv.setText(carInfo.Load + "吨" + "\n载重");
        shape_tv.setText(carInfo.Dimension + "m\n长*宽*高");
        bulk_tv.setText(carInfo.VolumeCargo + "方\n载货体积");
        initBanner(carInfo.ImageList);
    }


    private void initBanner(List<String> imgUrls) {
        //https://github.com/youth5201314/banner 教程地址
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
        //设置图片集合
        banner.setImages(imgUrls);
        //设置banner动画效果
        banner.setBannerAnimation(Transformer.DepthPage);
//        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(titles);
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(2500);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.price_details_tv:
                startAty(FareActivity.class);
                break;
            case R.id.order_now_btn://现在用车
                userCar("now");
                break;
            case R.id.order_appointment_layout://预约用车
                userCar("after");
                break;
            case R.id.send_layout://发货选择
                startAty(ShipmentsActivity.class);
                break;
            case R.id.receive_layout://收货选择
                startAty(ReceivingActivity.class);
                break;
        }
    }

    private void userCar(String time) {
        if (sendInfoEvent == null) {
            ToastUtil.show("你还未选择发货信息");
            return;
        }
        if (receiveInfoEvent == null) {
            ToastUtil.show("你还未选择收货信息");
            return;
        }

        Intent intent = new Intent(mActivity, EditLogisticsInfoActivity.class);
        intent.putExtra("send", sendInfoEvent);
        intent.putExtra("receive", receiveInfoEvent);
        intent.putExtra("carType", carInfo.Id + "");
        intent.putExtra("money", totle_money_tv.getText().toString());
        intent.putExtra("mileage", "5");
        intent.putExtra("time", time);
        intent.putExtra("location_send",location_send);
        intent.putExtra("location_receive",location_receive);
        startActivity(intent);
    }
}
